const Promise = require('bluebird');

module.exports = function ({AgencysSettles, SettlesLogs, UsersFinances, Users, sequelize}) {

    /**
     * 入账 V2
     */
    AgencysSettles.amountV2 = function (id, user_id) {
        return sequelize.transaction(function (t) {
            return AgencysSettles.update({is_amount: 1}, {
                where: {
                    id: id,
                    partner_id: user_id,
                    is_amount: 0,
                    is_payed: 0
                },
                transaction: t
            }).then(function (result) {
                if (!result[0]) {
                    return {success: false, message: '更新失败'};
                }
                return AgencysSettles.findOne({where: {id: id}, transaction: t}).then(function (agencysSettle) {
                    return UsersFinances.create({
                        partner_id: agencysSettle.partner_id,
                        user_id: agencysSettle.agency_id,
                        amount: agencysSettle.agency_amount,
                        type: 'In',
                        operation: 'AgencySettle',
                        by: 'AgencySettle',
                        is_amount: 1,
                        order_id: agencysSettle.id,
                        status: 'Successful'
                    }, {transaction: t}).then(function () {
                        return sequelize.query("update Users u set u.updated_at = NOW(), u.amount = u.amount + :amount where u.id = :user_id", {
                            replacements: {user_id: agencysSettle.agency_id, amount: agencysSettle.agency_amount},
                            transaction: t
                        }).then(function () {
                            if (agencysSettle.inviter_agency_id && agencysSettle.inviter_agency_amount) {
                                return UsersFinances.create({
                                    partner_id: agencysSettle.partner_id,
                                    user_id: agencysSettle.inviter_agency_id,
                                    amount: agencysSettle.inviter_agency_amount,
                                    type: 'In',
                                    operation: 'InviterAgencySettle',
                                    by: 'InviterAgencySettle',
                                    is_amount: 1,
                                    order_id: agencysSettle.id,
                                    note: agencysSettle.agency_id,
                                    status: 'Successful'
                                }, {transaction: t}).then(function () {
                                    return sequelize.query("update Users u set u.updated_at = NOW(), u.amount = u.amount + :amount where u.id = :user_id", {
                                        replacements: {
                                            user_id: agencysSettle.inviter_agency_id,
                                            amount: agencysSettle.inviter_agency_amount
                                        },
                                        transaction: t
                                    });
                                }).then(function () {
                                    return {success: true};
                                });
                            }
                            return {success: true};
                        });
                    });
                });
            });
        }).catch(function (e) {
            if (e) {
                console.error('\n', e.stack || e.message);
            }
            return {success: false, message: e.message || ''};
        });
    }

    /**
     * 批量入账 V2
     */
    AgencysSettles.batchAmountV2 = function (partner) {
        let where = partner ? {is_amount: 0, is_payed: 0, partner_id: partner.id} :
            {is_amount: 0, is_payed: 0, auto_amount: 1};
        return AgencysSettles.findAll({where: where, raw: true}).then(function (settles) {
            let ids = [];
            return Promise.mapSeries(settles, function (settle) {
                ids.push(settle.id);
                return AgencysSettles.amountV2(settle.id, settle.partner_id);
            }).then(function (results) {
                let successful = 0, failed = 0;
                for (let i in results) {
                    if (results[i].success) {
                        successful += 1;
                    } else {
                        failed += 1;
                    }
                }
                SettlesLogs.create({
                    opt: 'BatchAmount',
                    ext_data: JSON.stringify({
                        ids: ids,
                        successful: successful,
                        failed: failed
                    }),
                    user_id: partner ? partner.id : null
                });
                return {success: true, successful: successful, failed: failed};
            });
        });
    }

    /**
     * 支付成功 V2
     */
    AgencysSettles.payedV2 = function (id, user_id) {
        return AgencysSettles.update({is_payed: 1}, {
            where: {
                id: id,
                partner_id: user_id,
                is_amount: 0,
                is_payed: 0
            }
        }).then(function (result) {
            if (result[0]) {
                return {success: true}
            }
            return {success: false, message: '更新失败'};
        });
    }


    /**
     * 批量支付成功 V2
     */
    AgencysSettles.batchPayedV2 = function (partner) {
        let where = partner ? {is_amount: 0, is_payed: 0, partner_id: partner.id} : {is_amount: 0, is_payed: 0};
        return AgencysSettles.findAll({where: where, raw: true}).then(function (settles) {
            let ids = [];
            return Promise.mapSeries(settles, function (settle) {
                ids.push(settle.id);
                return AgencysSettles.payedV2(settle.id, settle.partner_id);
            }).then(function (results) {
                let successful = 0, failed = 0;
                for (let i in results) {
                    if (results[i].success) {
                        successful += 1;
                    } else {
                        failed += 1;
                    }
                }
                SettlesLogs.create({
                    opt: 'BatchPayed',
                    ext_data: JSON.stringify({
                        ids: ids,
                        successful: successful,
                        failed: failed
                    }),
                    user_id: partner ? partner.id : null
                });
                return {success: true, successful: successful, failed: failed};
            });
        });
    }
}